# -*- coding: utf-8 -*- 

import wx
import os
import re
import requests
import urllib3

#import other code
def downloadPic(html,keyword):
    pic_url = re.findall('"objURL":"(.*?)",',html,re.S)
    i = 0
    print 'Finding, now start...'
    for each in pic_url:
        print 'list '+str(i+1)+', address:'+str(each)
        try:
            pic= requests.get(each, timeout=5)
        #except requests.exceptions.ConnectionError:
        except:
            continue
        #number = random.randint(1001, 9999)
        path = 'C:/Users/Administrator/Desktop/pictures/'+keyword
        mk_dir(path.decode('utf-8').encode('gbk'))
        filetype = each.encode('utf-8').split('/')
        filename = path+'/'+str(i)+'_'+filetype[-1]
        #resolve the problem of encode, make sure that chinese name could be store
        filename = filename.decode('utf-8').encode('gbk')
        if not os.path.exists(filename):
            try:
                fp = open(filename,'wb')
                fp.write(pic.content)
                fp.close()
            except:
                continue
        i += 1

def mk_dir(path):  
    isExisist = os.path.exists(path)  
    if not isExisist:  
        os.makedirs(path)  
        return True  
    else:  
        return False 

#import the newly created GUI file 
import main  
class CalcFrame(main.MyFrame1): 
    def __init__(self,parent): 
        main.MyFrame1.__init__(self,parent) 

    def download(self,event): 
        text1 = (self.m_textCtrl1.GetValue())
        text2 = (self.m_textCtrl2.GetValue())
        word = text1.encode('utf-8')
        page = text2.encode('utf-8')
        for i in range(0,int(page)):
            pn = str(20*i)
            url = 'http://image.baidu.com/search/flip?tn=baiduimage&fm=result&ie=utf-8&word='+word+'&pn='+pn
            result = requests.get(url)
            downloadPic(result.text,word)

#run code
app = wx.App(False) 
frame = CalcFrame(None) 
frame.Show(True) 
#start the applications 
app.MainLoop()  